package com.cheejee.goodscenter.util;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cheejee.goodscenter.dao.GoodsSaleTaskMapper;
import com.cheejee.goodscenter.dao.GoodsUpDownTaskMapper;

import cn.hutool.cron.CronUtil;

/**
 * @author CARRY
 * @Date 2020年10月27日下午3:56:36
 */
public class TaskUtil {

	@Resource
	private GoodsUpDownTaskMapper udm;

	@Resource
	private GoodsSaleTaskMapper sm;

	private Map<Long, List<String>> upDownTaskId;
	private Map<Long, String> saleTaskId;

	/**
	 * 启动定时任务，把这个方法放到springboot启动类下面
	 */
	public void startTask() {
		startUpDownTask();
		startSaleTask();
	}

	private void startUpDownTask() {
		udm.selectBySelective(null, null, null, Date.from(Instant.now())).forEach(t -> {

			String id = CronUtil.schedule(String.valueOf(t.getId()), getUdtCron(t.getExecuteTime()), new GoodsUpAndDownTask(t.getGoodsId(), t.getType()));

			List<String> ids = upDownTaskId.get(t.getGoodsId());
			if (ids == null) {
				upDownTaskId.put(t.getGoodsId(), Arrays.asList(id));
			} else {
				ids.add(id);
				upDownTaskId.put(t.getGoodsId(), ids);
			}
		});
	}

	private void startSaleTask() {
		sm.selectBySelective(null, null).forEach(t -> {
			String id = CronUtil.schedule(String.valueOf(t.getId()), t.getCron(), new GoodsSaleTask(t.getGoodsId()));
			saleTaskId.put(t.getGoodsId(), id);
		});
	}

	/***
	 * 获取商品上下架定时表达式
	 * 
	 * @param date
	 * @return
	 */
	public static String getUdtCron(Date date) {
		return new SimpleDateFormat("ss mm HH dd MM ? yyyy").format(date);
	}

	/***
	 * 获取商品销量更新定时表达式
	 * 
	 * @param date : 时间点
	 * @return
	 */
	public static String getSaleCron(Date date) {
		String formatTimeStr = new SimpleDateFormat("ss mm HH").format(date);
		StringBuffer sb = new StringBuffer(formatTimeStr);
		sb.append(" */1 * ?");

		return sb.toString();
	}
}
